<!--
 * @Author: 卢景滔
 * @Date: 2021-12-20 17:21:11
 * @LastEditTime: 2021-12-22 09:38:17
 * @LastEditors: 卢景滔
 * @Description: worker使用
-->
<template>
  <div><h1>worker使用</h1></div>
</template>

<script>
export default {
  created() {
    // 兼容性判断
    if (!window.Worker) {
      throw new Error('当前浏览器不支持多线程')
    }

    // 创建子线程
    this.childThread = new Worker('/worker/ChildThread.js')

    // 向子线程发送数据
    this.childThread.postMessage('How are you?')

    // 监听子线程信息
    this.childThread.addEventListener('message', this.messageHandle)
  },
  methods: {
    // 消息处理
    messageHandle(e) {
      console.log('Worker主线程收到子线程信息: ', e.data)
    },
  },
  destroyed() {
    // 记得销毁线程
    this.childThread.removeEventListener('message', this.messageHandle)
    this.childThread.terminate()
  },
}
</script>
